import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/common/components/index.dart';
import 'package:getx_scaffold/common/index.dart';

class BlueLogic extends GetxController {
  static BlueLogic get to =>Get.find();
  // 蓝牙设备状态
  final isScanning = false.obs;
  final connectedDevice = Rx<BluetoothDevice?>(null);
  final scanResults = <ScanResult>[].obs;

  // 助听器状态数据
  final leftEarConnected = false.obs;
  final rightEarConnected = false.obs;
  final leftEarBattery = 0.obs;
  final rightEarBattery = 0.obs;
  final workMode = 1.obs; // 1:强降噪 2:室内 3:室外 4:自定义
  final leftEarVolume = 3.obs;
  final rightEarVolume = 3.obs;
  final freq500Hz = 0.obs;
  final freq1kHz = 0.obs;
  final freq2kHz = 0.obs;
  final freq3kHz = 0.obs;
  final freq4kHz = 0.obs;

  // 特征值
  BluetoothCharacteristic? characteristic;
  BluetoothCharacteristic? valueCharacteristic;
  StreamSubscription<List<int>>? valueSubscription;

  @override
  void onInit() {
    super.onInit();
    // 初始化蓝牙
    initBluetooth();
  }

  @override
  void onClose() {
    // 取消订阅
    valueSubscription?.cancel();
    // 断开连接
    if (connectedDevice.value != null) {
      connectedDevice.value!.disconnect();
    }
    super.onClose();
  }

  // 初始化蓝牙
  Future<void> initBluetooth() async {
    // 监听蓝牙状态
    FlutterBluePlus.adapterState.listen((state) {
      if (state == BluetoothAdapterState.on) {
        // 蓝牙已开启
        startScan();
      }
    });
  }

  // 开始扫描
  Future<void> startScan() async {
    if (isScanning.value) return;

    // 设置扫描状态
    isScanning.value = true;

    try {
      // 开始扫描
      await FlutterBluePlus.startScan(timeout: const Duration(seconds: 15));

      // 监听扫描结果
      FlutterBluePlus.scanResults.listen((results) {
        // 清空扫描结果
        scanResults.clear();

        // 打印扫描结果
        for (var result in results) {
          if (result.device.name.isNotEmpty) {
            // print('${result.device.name} - ${result.device.id.id}');
            scanResults.add(result);
          } else {
            // print('${result.device.id.id}');
          }
        }

        // scanResults.value = results;
      });

      // 监听扫描状态
      FlutterBluePlus.isScanning.listen((scanning) {
        isScanning.value = scanning;
      });
    } catch (e) {
      print('扫描出错: $e');
      isScanning.value = false;
    }
  }

  // 开始扫描
  Future<void> startScanAndConnect() async {
    if (isScanning.value) return;

    // 设置扫描状态
    isScanning.value = true;

    try {
      // 开始扫描
      await FlutterBluePlus.startScan(timeout: const Duration(seconds: 15));

      // 监听扫描结果
      FlutterBluePlus.scanResults.listen((results) {
        // 清空扫描结果
        scanResults.clear();
        BluetoothDevice? device;
        // 打印扫描结果
        for (var result in results) {
          if (result.device.name.isNotEmpty) {
            // print('${result.device.name} - ${result.device.id.id}');
            scanResults.add(result);
            device = result.device;
            break;
          } else {
            // print('${result.device.id.id}');
          }
        }
        if (device != null) {
          connectToDevice(device);
        }
        // scanResults.value = results;
      });

      // 监听扫描状态
      FlutterBluePlus.isScanning.listen((scanning) {
        isScanning.value = scanning;
      });
    } catch (e) {
      print('扫描出错: $e');
      isScanning.value = false;
    }
  }

  // 停止扫描
  Future<void> stopScan() async {
    if (!isScanning.value) return;

    try {
      await FlutterBluePlus.stopScan();
    } catch (e) {
      print('停止扫描出错: $e');
    }
  }

  // 连接设备
  Future<void> connectToDevice(BluetoothDevice device) async {
    try {
      // Loading.show('连接中...');
      await device.connect();
      connectedDevice.value = device;

      // 发现服务
      await discoverServices(device);
      // Loading.dismiss();
      Toast.show('连接成功');
    } catch (e) {
      print('连接设备出错: $e');
      //Get.snackbar('连接失败', '无法连接到设备: ${device.name}');
    }
  }

  // 断开连接
  Future<void> disconnectDevice() async {
    if (connectedDevice.value == null) return;

    try {
      await connectedDevice.value!.disconnect();
      connectedDevice.value = null;
      characteristic = null;
      valueCharacteristic = null;
      valueSubscription?.cancel();
      valueSubscription = null;
    } catch (e) {
      print('断开连接出错: $e');
    }
  }

  // 发现服务
  Future<void> discoverServices(BluetoothDevice device) async {
    try {
      List<BluetoothService> services = await device.discoverServices();

      // 查找特征值
      for (var service in services) {
        for (var char in service.characteristics) {
          // 这里需要根据实际情况设置特征值UUID
          // 假设我们知道助听器的特征值UUID
          //e49a28e1-f69a-11e8-8eb2-f2801f1b9fd1
          if (char.properties.notify || char.properties.indicate) {
            valueCharacteristic = char;
            // 订阅特征值变化
            valueSubscription = char.lastValueStream.listen((value) {
              // 解析状态数据
              parseStatusData(value);
            });

            break;
          }
        }
        if (valueCharacteristic != null) break;
      }

      // 查找特征值
      for (var service in services) {
        for (var char in service.characteristics) {
          // 这里需要根据实际情况设置特征值UUID
          // 假设我们知道助听器的特征值UUID
          //e49a25e0-f69a-11e8-8eb2-f2801f1b9fd1
          if (char.properties.write || char.properties.writeWithoutResponse) {
            characteristic = char;

            // 获取初始状态
            getStatus();
            break;
          }
        }
        if (characteristic != null) break;
      }
    } catch (e) {
      print('发现服务出错: $e');
    }
  }

  // 解析状态数据
  void parseStatusData(List<int> value) async {
    print('接收到数据: $value');

    // 确保数据长度足够且符合协议格式
    if (value.length >= 14 &&
        value[0] == 0xFF &&
        value[1] == 0xFF &&
        value[2] == 0x00) {
      print(
          '解析状态数据: 左耳连接=${value[3] == 1}, 右耳连接=${value[4] == 1}, 左耳电量=${value[5]}, 右耳电量=${value[6]}');

      leftEarConnected.value = value[3] == 1;
      rightEarConnected.value = value[4] == 1;
      leftEarBattery.value = value[5];
      rightEarBattery.value = value[6];
      workMode.value = value[7];
      leftEarVolume.value = value[8];
      rightEarVolume.value = value[9];
      freq500Hz.value = value[10];
      freq1kHz.value = value[11];
      freq2kHz.value = value[12];
      freq3kHz.value = value[13];
      freq4kHz.value = value[14];
      await valueCharacteristic!.setNotifyValue(false);
    } else {
      print('数据格式不符合协议要求或长度不足: $value');
    }
  }

  // 获取状态数据
  Future<void> getStatus() async {
    if (characteristic == null) return;

    try {
      print('发送获取状态命令: [0xAA, 0x00, 0x03]');
      await characteristic!.write([0xAA, 0x00, 0x03],
          withoutResponse: characteristic!.properties.writeWithoutResponse);

      // 读取最新状态
      _readValue();
    } catch (e) {
      print('获取状态出错: $e');
    }
  }

  // 调节音量增益
  Future<void> setVolume(int ear, int volume) async {
    if (characteristic == null || volume < 1 || volume > 5) return;

    try {
      await characteristic!.write([0xAA, 0x01, ear, volume],
          withoutResponse: characteristic!.properties.writeWithoutResponse);

      // 更新本地状态
      if (ear == 0x01 || ear == 0x03) {
        leftEarVolume.value = volume;
      }
      if (ear == 0x02 || ear == 0x03) {
        rightEarVolume.value = volume;
      }

      // 读取最新状态
      await _readValue();

      //Get.snackbar('成功', '设置音量成功', backgroundColor: Colors.green.withOpacity(0.3));
    } catch (e) {
      print('设置音量出错: $e');
      //Get.snackbar('失败', '设置音量失败: $e', backgroundColor: Colors.red.withOpacity(0.3));
    }
  }

  // 切换工作模式
  Future<void> setWorkMode(int ear, int mode) async {
    if (characteristic == null || mode < 1 || mode > 4) return;

    try {
      await characteristic!.write([0xAA, 0x02, ear, mode],
          withoutResponse: characteristic!.properties.writeWithoutResponse);

      // 更新本地状态
      workMode.value = mode;

      // 读取最新状态
      await _readValue();

      //Get.snackbar('成功', '设置模式成功', backgroundColor: Colors.green.withOpacity(0.3));
    } catch (e) {
      print('设置模式出错: $e');
      //Get.snackbar('失败', '设置模式失败: $e', backgroundColor: Colors.red.withOpacity(0.3));
    }
  }

  // 设置频率增益
  Future<void> setFrequencyGain(int ear, int freqType, int gain) async {
    if (characteristic == null ||
        freqType < 0x80 ||
        freqType > 0x84 ||
        gain < -12 ||
        gain > 12) return;

    try {
      // 将-12到12的增益值转换为0-24的值进行传输
      int adjustedGain = gain + 12;
      await characteristic!.write([0xAA, 0x03, ear, freqType, adjustedGain],
          withoutResponse: characteristic!.properties.writeWithoutResponse);

      // 更新本地状态
      switch (freqType) {
        case 0x80:
          freq500Hz.value = gain;
          break;
        case 0x81:
          freq1kHz.value = gain;
          break;
        case 0x82:
          freq2kHz.value = gain;
          break;
        case 0x83:
          freq3kHz.value = gain;
          break;
        case 0x84:
          freq4kHz.value = gain;
          break;
      }

      // 读取最新状态
      await _readValue();

      //Get.snackbar('成功', '设置频率增益成功', backgroundColor: Colors.green.withOpacity(0.3));
    } catch (e) {
      print('设置频率增益出错: $e');
      //Get.snackbar('失败', '设置频率增益失败: $e', backgroundColor: Colors.red.withOpacity(0.3));
    }
  }

  // 恢复出厂设置
  Future<void> resetDevice() async {
    if (characteristic == null) return;

    try {
      await characteristic!.write([0xAA, 0x04, 0x03],
          withoutResponse: characteristic!.properties.writeWithoutResponse);

      // 读取最新状态
      await _readValue();

      //Get.snackbar('成功', '恢复出厂设置成功', backgroundColor: Colors.green.withOpacity(0.3));
    } catch (e) {
      print('恢复出厂设置出错: $e');
      //Get.snackbar('失败', '恢复出厂设置失败: $e', backgroundColor: Colors.red.withOpacity(0.3));
    }
  }

  Future<void> _readValue() async {
    if (valueCharacteristic!.properties.read) {
      await valueCharacteristic!.setNotifyValue(true);
      print('读取特征值数据');
      await valueCharacteristic!.read();
    }
  }

  // 获取工作模式名称
  String getWorkModeName(int mode) {
    switch (mode) {
      case 1:
        return '强降噪';
      case 2:
        return '室内';
      case 3:
        return '室外';
      case 4:
        return '自定义';
      default:
        return '未知';
    }
  }
}
